package com.itcam.heapsort;

import cn.hutool.core.date.StopWatch;

import java.util.Arrays;

public class HeapSort {
    public static void main(String[] args) {
        int[] arr = {12, 11, 13, 5, 6, 7};
        System.out.println(Arrays.toString(arr));
        heapSort(arr, arr.length - 1);
        System.out.println(Arrays.toString(arr)); // [5, 6, 7, 11, 12, 13]
    }

    public static void heapSort(int[] arr, int len) {

        // 1.建大顶堆
        for (int root = len / 2 - 1; root >= 0; root--) {
            heapify(arr, len, root);
        }
        // {12, 11, 13, 5, 6, 7}
        //          13
        //         /  \
        //       12    11
        //      / \    / \
        //     7   6  5

        // 2.建小顶堆
        for (int child = len; child > 0; child--) {
            swap(arr, 0, child);
            heapify(arr, child, 0);
        }

    }

    // 金字塔维护术：让父节点大于子节点（大顶堆）
    private static void heapify(int[] arr, int len, int root) {
        int max = root;
        int leftChild = 2 * root + 1;
        int rightChild = 2 * root + 2;
        if (leftChild < len && arr[leftChild] > arr[max]) {
            max = leftChild;
        }
        if (rightChild < len && arr[rightChild] > arr[max]) {
            max = rightChild;
        }
        if (max != root) {
            swap(arr, max, root);
            heapify(arr, len, max);
        }
    }

    private static void swap(int[] arr, int i, int j) {
        int temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }
}